package com.mmc.delay.ui.service;

import com.mmc.delay.api.DelayFacade;
import com.mmc.delay.bean.DeadJob;
import com.mmc.delay.bean.Job;
import com.mmc.delay.ui.bean.Pager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class RedisDelayAdminServiceImpl implements RedisDelayAdminService {

    @Autowired
    private DelayFacade delayFacade;

    private static final Logger logger = LoggerFactory.getLogger(RedisDelayAdminServiceImpl.class);

    @Override
    public Pager<List<Job>> queryDelayData(String topic, Integer pageNo, Integer pageSize) {
        Integer start=(pageNo-1)*pageSize;
        Integer end=pageNo*pageSize-1;
        List<Job> list = delayFacade.queryDelayData(topic, Long.valueOf(start), Long.valueOf(end));
        Long recordNum = delayFacade.queryDelayRecordNum(topic);
        Pager<List<Job>> pager=new Pager(recordNum.intValue(),list);
        return pager;
    }

    @Override
    public Pager<List<DeadJob>> queryDeadData(String topic, Integer pageNo, Integer pageSize) {
        Integer start=(pageNo-1)*pageSize;
        Integer end=pageNo*pageSize-1;
        List<DeadJob> list = delayFacade.queryDeadData(topic, Long.valueOf(start), Long.valueOf(end));
        Long recordNum = delayFacade.queryDeadRecordNum(topic);
        Pager<List<DeadJob>> pager=new Pager(recordNum.intValue(),list);
        return pager;
    }

    @Override
    public List<Job> queryJobPool() {
        return null;
    }

    @Override
    public Job queryJobById(String jobId) {
        return null;
    }

    @Override
    public Map<String, Boolean> queryAllTopicStatus() {
        Set<String> allTopic = delayFacade.queryAllTopics();
        Set<String> stopTopics = delayFacade.queryStopTopics();
        Map<String,Boolean> result=new HashMap<>();
        for (String topic:allTopic){
            result.put(topic,!stopTopics.contains(topic));
        }
        return result;
    }

    @Override
    public boolean deadMessageReTry(DeadJob deadJob) {
        Job job=new Job();
        BeanUtils.copyProperties(deadJob,job);
        job.setCurrentRetryCount(job.getRetries());
        job.setRetries(job.getRetries()+1);
        boolean result=delayFacade.tryRetry(job);
        if(result){
            delayFacade.removeDeadJob(deadJob);
        }
        return result;
    }

    @Override
    public void stopTopic(String topic) {
        logger.info("停止topic[{}]",topic);
        delayFacade.stopTopic(topic);
    }

    @Override
    public void startTopic(String topic) {
        logger.info("开始topic[{}]",topic);
        delayFacade.startTopic(topic);
    }
}
